﻿namespace EFS.AD.Misc
{
	public static class Functions
	{
		/// GetDirectoryEntryStringValue
		public static System.String GetDirectoryEntryStringValue(
			System.DirectoryServices.DirectoryEntry directoryEntry,
			System.String propertyName)
		{
			// check
			EFS.Common.Verify.Reference(directoryEntry, "directoryEntry");
			EFS.Common.Verify.String(propertyName, "propertyName");

			// get name/value
			System.DirectoryServices.PropertyValueCollection nameValue = directoryEntry.Properties[propertyName];
			if (null != nameValue && null != nameValue.Value)
			{
				return nameValue.Value.ToString().Trim();
			}

			// none
			return null;
		}

		/// GetDirectoryEntryStringValue
		public static System.Guid? GetDirectoryEntryGuidValue(
			System.DirectoryServices.DirectoryEntry directoryEntry,
			System.String propertyName)
		{
			// check
			EFS.Common.Verify.Reference(directoryEntry, "directoryEntry");
			EFS.Common.Verify.String(propertyName, "propertyName");

			// get name/value
			System.DirectoryServices.PropertyValueCollection nameValue = directoryEntry.Properties[propertyName];
			if (null != nameValue && null != nameValue.Value)
			{
				// be sure if byte[] type
				if (nameValue.Value is System.Byte[])
				{
					return new System.Guid((System.Byte[])nameValue.Value);
				}
			}

			// none
			return null;
		}

		/// Load user
		public static EFS.AD.User UserFrom(System.DirectoryServices.DirectoryEntry directoryEntry)
		{
			// check
			EFS.Common.Verify.Reference(directoryEntry, "directoryEntry");

			// get object guid
			System.Guid? objectGuid = EFS.AD.Misc.Functions.GetDirectoryEntryGuidValue(directoryEntry, "objectGUID");
			EFS.Common.Verify.Condition(objectGuid.HasValue, "objectGuid.HasValue");
			EFS.Common.Verify.Guid(objectGuid.Value, "objectGuid.Value");

			// ok
			EFS.AD.User user = new EFS.AD.User(
					objectGuid.Value,
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "sAMAccountName"),
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "Mail"),
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "msRTCSIP-PrimaryUserAddress"),
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "msRTCSIP-Line"),
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "givenName"),
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "sn"),
					EFS.AD.Misc.Functions.GetDirectoryEntryStringValue(directoryEntry, "description"));
			// done
			return user;
		}
	}

}